package com.geek.aidy.geek.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import com.geek.aidy.geek.T;
import com.geek.aidy.geek.annotation.Desensitize;
import com.geek.aidy.geek.enums.DesensitizeType;

public class DesensitizeProcessorUtil {

    /**
     * 处理 List 对象集合，根据字段注解的类型来决定是否处理
     *
     * @param inputList 输入的 List 对象集合
     * @param processor 处理函数
     * @return 处理后的 List 对象集合
     */
    public List<T> processList(List<T> inputList) {
        List<T> outputList = new ArrayList<>();
        for (T item : inputList) {
            outputList.add(processField(item));
        }
        return outputList;
    }


    // 根据字段的注解类型进行处理
    public T processField(T item) {
    
        Field[] fields = item.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Desensitize.class)) {
                field.setAccessible(true); // 允许访问私有字段
                try {
                    Desensitize desensitize = field.getAnnotation(Desensitize.class);
                    String value = (String) field.get(item);
                    String processedValue = null;

                    processedValue = desensitizeValue(value, desensitize.type());

                    // 将处理后的值设置回字段
                    field.set(item, processedValue);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return item;
    }

    private String desensitizeValue(String value, DesensitizeType type) {
        switch (type) {
            case NAME:
                return desensitizeName(value);
            case PHONE:
                return desensitizePhone(value);
            default:
                return value;
        }
    }

    private String desensitizeName(String name) {
        if (name == null || name.isEmpty()) {
            return name;
        }
        return name.replaceAll("^(\\S).*", "$1*");
    }

    private String desensitizePhone(String phone) {
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

}
